<?php

namespace app\api\controller\User;

use PHPMailer\PHPMailer\PHPMailer;
use think\Controller;

class Base extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
    }

    // 注册
    public function register()
    {
        $email = $this->request->param('email','');

        $password = $this->request->param('password','');

        // 注册时赠送的积分 商城的数据库 => 论坛的数据库
        $RegisterPoint = model('Config')->where('key','RegisterPoint')->value('value');

        // 生成密码盐
        $salt = build_ranstr();

        // 加密
        $password = md5($password.$salt);

        // 封装数据
        $data = [
            'email' => $email,
            'password' => $password,
            'salt' => $salt,
            'point' => $RegisterPoint,
            'sex' => 0,
            'auth' => 0,
            'vip' => 1,
        ];

        // 插入数据库
        $result = $this->UserModel->validate('common/User/User.vue')->save($data);

        if($result === FALSE)
        {
            $this->error($this->UserModel->getError());
        }else{
            $this->success('注册成功','/user/base/login');
        }
    }

    public function login()
    {
        $params = $this->request->param();

        $User = $this->UserModel->where(['email' => $params['email']])->find();

        if(!$User)
        {
            $this->error('该用户不存在');
        }

        // 密码
        $password = md5($params['password'].$User['salt']);

        if($password != $User['password'])
        {
            $this->error('密码错误');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text']
        ];
		
		// header('Content-Type:application/json; charset=utf-8');
		
		// return json_encode($data);

        $this->success('登录成功','/user/base/index',$data);
    }

    public function check()
    {
        $userid = $this->request->param('userid');

        $User = $this->UserModel->find($userid);

        if(!$User)
        {
            $this->error('非法登录');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text']
        ];

        $this->success('认证成功',null,$data);
    }
	// vue修改个人信息
    public function profile()
    {
        $params = $this->request->param();

        $user = $this->UserModel->find($params['id']);

        if(!$user)
        {
            $this->error('用户不存在');
        }

        // 封装数据
        $data = [
            'id' => $params['id'],
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];

        if(isset($params['code']))
        {
            $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');

            if(!$parentpath)
            {
                $this->error('所选地区不存在');
            }

            [$province,$city,$district] = explode(',',$parentpath);

            if($province)
            {
                $data['province'] = $province;
            }

            if($city)
            {
                $data['city'] = $city;
            }

            if($district)
            {
                $data['district'] = $district;
            }
        }

        if(!empty($params['password']))
        {
            // 密码盐
            $salt = build_ranstr();

            // 加密
            $data['password'] = md5($params['password'].$salt);

            $data['salt'] = $salt;
        }

        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            $avatar = upload('avatar');

            if($avatar['code'] == 0)
            {
                $this->error($avatar['msg']);
            }

            $data['avatar'] = $avatar['data'];
        }

        if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
        {
            $cover = upload('cover');

            if($cover['code'] == 0)
            {
                $this->error($cover['msg']);
            }

            $data['cover'] = $cover['data'];
        }

        $result = $this->UserModel->isUpdate(true)->save($data);

        if($result === FALSE)
        {
            if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
            }

            if(isset($data['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
            }

            $this->error('修改失败');

        }else{
            if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file('.' . $user['cover']) && unlink('.' . $user['cover']);
            }

            if(isset($data['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                @is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
            }

            $User = $this->UserModel->find($params['id']);

            $UserData = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar' => $User['avatar_cdn'],
                'cover' => $User['cover_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'region_text' => $User['region_text']
            ];

            $this->success('修改成功','/user/base/index',$UserData);
        }

    }
	// 发送邮箱
	public function code()
	{
		$userid = $this->request->param('userid');

		$email = $this->request->param('email');

		$User = $this->UserModel->find($userid);

		if(!$User)
		{
			$this->error('该用户不存在');
		}

		if($email != $User['email'])
		{
			$this->error('该邮箱不存在');
		}

		$code = build_ranstr(4);

		session($User['id'],$code);

		$content = "验证码：$code";

		$mail = new PHPMailer(true);

		// 开启SMTP
		$mail->isSMTP(true);

		// SMTP服务器 qq => smtp.qq.com
		$mail->Host = "smtp.163.com";

		// 开启认证
		$mail->SMTPAuth = true;

		// 发送内容支持HTML
		$mail->IsHTML(true);

		// 账号
		$mail->Username = 'D1090300992@163.com';

		// 密码 => 不是邮箱密码，开启SMTP时的授权码
		$mail->Password = 'DTLNZYEANSWZYVWH';

		// 端口 服务器需要465端口
		$mail->Port = 465;

		// 协议
		$mail->SMTPSecure = 'ssl';

		// 发件邮箱
		$mail->From = 'D1090300992@163.com';

		// 发件人名字
		$mail->FromName = "ASK论坛";

		// 接收回复的邮箱
		$mail->addReplyTo('D1090300992@163.com',"ASK论坛");

		// 收件人
		$mail->addAddress($User['email'],$User['nickname']);

		// 邮箱主题
		$mail->Subject = '账号认证';

		//设置多少个字符换行 80字符
		$mail->WordWrap = 80;

		// 发送HTML内容
		$mail->msgHTML($content);

		$result = $mail->send();

		if($result === FALSE)
		{
			$this->error('发送邮件失败');
		}else {
			$this->success('发送邮件成功');
		}

	}
	
	public function echeck()
	{
		$userid = $this->request->param('userid');

		$code = $this->request->param('code');

		$user = $this->UserModel->find($userid);

		if(!$user)
		{
			$this->error('该用户不存在');
		}

		$check = session($user['id']);

		if($code != $check)
		{
			$this->error('验证码错误');
		}

		$data = [
			'id' => $user['id'],
			'auth' => 1
		];

		$result = $this->UserModel->isUpdate(true)->save($data);

		if($result === FALSE)
		{
			$this->error('验证失败');
		}else{
			$this->success('验证成功','/user/base/index');
		}
	}
	
	
	public function wx()
	{
		$userid = $this->request->param('id');

		$User = $this->UserModel->find($userid);

		if(!$User)
		{
			// $this->error('您未绑定账号，请绑定');
			return json(['code' => 0,'msg' => '您未绑定账号，请绑定']);
		}else{
			// $this->success('查询成功',null,$User);
			return json(['code' => 1,'msg' => '查询成功','data' => $User]);
		}
	}
	
	public function wxlogin()
	{
		$code = $this->request->param('code');

		if(!$code)
		{
			return json(['code' => 0,'msg' => '授权失败']);
		}

		$ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=wx0caf0fd76a74e2fd&secret=3672e66572aefc232b175ebd6b0ad342&js_code=$code&grant_type=authorization_code";

		$result = $this->https_request($ApiUrl);
	
		$result = json_decode($result,true);

		$openid = isset($result['openid']) ? $result['openid'] : '';
		
		if(empty($openid))
		{
			return json(['code' => 0,'msg' => '获取凭证失败']);
		}

		$User = $this->UserModel->where(['openid' => $openid])->find();

		if(!$User)
		{
			return json(['code' => 0,'msg' => '您未绑定账号，请绑定']);
		}

		return json(['code' => 1 , 'msg' => '登录成功','data' => $User]);

	}


	private function https_request($url,$data = null)
	{
		if(function_exists('curl_init')){
		$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
			curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
			if (!empty($data)){
				curl_setopt($curl, CURLOPT_POST, 1);
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($curl);
			curl_close($curl);
			return $output;
		}else{
			return false;
		}
	}
	
}
